#ifndef P_MATERIAL_COMPONENT_H
#define P_MATERIAL_COMPONENT_H

#include "Render/PMaterial.h"
#include "Render/PiccoloMesh.h"
#include "ECS/Component/PComponent.h"

namespace Piccolo
{
    template<typename T>
    class PMaterialComponent : public PComponent
    {
    public:
        void AddMesh(PiccoloMesh* mesh, T* material = nullptr)
        {
            if (!mesh) return;
            uint32_t meshIndex = mMeshList.size();
            mMeshList.push_back(mesh);

            if (mMeshMaterials.find(material) != mMeshMaterials.end())
            {
                mMeshMaterials[material].push_back(meshIndex);
            }
            else
            {
                mMeshMaterials.insert({ material, { meshIndex } });
            }
        }

        uint32_t GetMaterialCount() const
        {
            return mMeshMaterials.size();
        }

        const std::unordered_map<T*, std::vector<uint32_t>>& GetMeshMaterials() const
        {
            return mMeshMaterials;
        }

        PiccoloMesh* GetMesh(uint32_t index) const
        {
            if (index < mMeshList.size())
            {
                return mMeshList[index];
            }
            return nullptr;
        }

    private:
        // 使用到该材质的所有mesh实例
        std::vector<PiccoloMesh*> mMeshList;
        // key表示材质的指针，value表示使用这个材质的mesh实例的索引
        std::unordered_map<T*, std::vector<uint32_t>> mMeshMaterials;
    };
}

#endif